#! /usr/bin/env python
#coding=utf-8

# pylint: disable-msg=W0704

# Copyright 2008 German Aerospace Center (DLR)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" restrain the format of commit message. """

'''
    # 该文件可以被放置在诸如 /opt/gitlab/embedded/service/gitlab-shell/hooks/pre-receive.d 目录下, 直接使用
'''

import datetime
import re
from urllib import urlopen
import json

import sys
import subprocess



#print("argv", sys.argv)

#args = sys.stdin.readline().strip().split(' ')
#print(args)

##########################################################################
# 参考: https://georgestocker.com/2017/01/04/how-do-i-require-specific-text-in-a-git-commit-message/
##########################################################################


def _analysisCommitMsg(commitMsg):
    commitMsgBylines = commitMsg
    if(len(commitMsgBylines) < 1):
        return (_formatErrorInfo("日志的行数不足"), 1)

    firstLine = commitMsgBylines[0].strip()
    print("08888", firstLine)
    if "FORCE" in firstLine or "Merge branch" in firstLine:
        return ("强制提交, PASS", 0)
    patt = re.compile("[story|bug|task]\:\d+\s.+")
    result = re.search(patt,firstLine)
    print("3333", result)
    if(result == None):
        return (_formatErrorInfo("日志的格式不对, 形如：story:31604 增加返回字段信息。具体请参考：http://oa.kqgeo.com:1890/pages/viewpage.action?pageId=38339077"), 1)

    if(not _existIdInZentao(firstLine)):
        return (_formatErrorInfo("不存在该zentao ID, 请确认"), 1)
    return ("",0)

def _existIdInZentao(firstLineOfMsg):
    arr = firstLineOfMsg.split(" ")[1].split(":")
    print("9999",arr, firstLineOfMsg)
    type = arr[0]
    id = arr[1]
    return zentao(type, id)


BASE_URL="http://xxx.yy.zz.cc:80/zentao"
PASSWORD=r"cccYYYXXX"

def zentao(type, id):
    sessionResult = zentao_getSessionInfo()
    sessionName = sessionResult["sessionName"]
    sessionID = sessionResult["sessionID"]
    rand = sessionResult["rand"]
    zentao_userLogin(sessionResult)
    return zentao_checkIfExistId(type,id,sessionID)

def zentao_getSessionInfo():
    response = urlopen('{}/api-getSessionID.json'.format(BASE_URL))
    #print(type(response.read()))
    #print(type(response.read().decode("UTF-8")))
    #print(json.loads(response.read().decode("UTF-8"))["data"])
    sessionResult = json.loads(response.read().decode("UTF-8"))["data"]
    return json.loads(sessionResult)

def zentao_userLogin(sessionResult):
    response = urlopen('{}/user-login.json?account=luoqi&password={}&{}={}'.format(BASE_URL,PASSWORD,sessionResult["sessionName"],sessionResult["sessionID"]))
    result = json.loads(response.read().decode("UTF-8"))
    #print("tjx-1111-", result)
    if(result["status"] == "failed"):
        raise Exception(result["reason"])
    else:
        pass

def zentao_checkIfExistId(type, id,sessionID):
    response = urlopen('{}/{}-view-{}.json?zentaosid={}'.format(BASE_URL, type, id, sessionID))
    result = response.read().decode("UTF-8")

    #print("tjx-2222-",result)
    return not ("fail" in result and "back" in result)




def _formatErrorInfo(errorInfo):
    return ("日志格式存在问题: " + errorInfo) #.decode("utf-8").encode("gbk")


def isInRuleProject(ruleProjectPathArr,projectPath):
    for ruleProjectPath in ruleProjectPathArr:
         if(ruleProjectPath in projectPath):
            return True
    return False

################################################################################# Begin
#proc = subprocess.Popen('git ls-remote', stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT)
#proc = subprocess.Popen('git log -n 1', stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT)
#proc = subprocess.Popen("git config --global user.name", stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT)
#proc = subprocess.Popen("git config --global user.email", stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT)

#proc = subprocess.Popen('git rev-parse --abbrev-ref HEAD', stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT)
#proc = subprocess.Popen('git log', stdout=subprocess.PIPE, shell=True, stderr=subprocess.STDOUT)
#lines = proc.stdout.readlines()
#print("0111111", lines)

#import os
#print(os.getenv("GL_PROJECT_PATH"))

#if not "joint3.0" in os.getenv("GL_PROJECT_PATH"):
#  exit(0)

projectPath = os.getenv("GL_PROJECT_PATH")
if not projectPath:
  exit(0)

ruleProjectPathArr=['xx.0/','xx/','xxx/','cg/','zzz/','ccc/','kkk/']
if(not isInRuleProject(ruleProjectPathArr,projectPath)):
  exit(0)


print(os.getenv("GL_PROJECT_PATH"))
#exit(1)

#Format: "oldref newref branch"
line = sys.stdin.read()
(base, commit, ref) = line.strip().split()
print("4444", base, commit, ref)
# 全新分支将以00000为commit Id, 但我遇到的情况并不完全是这样, 因此这里取消这条判断
new_branch_push = base.startswith("00000000000000") #False # re.match(r'[^1-9]+', base)
# 被删除的分支 commit Id 也为 00000
branch_deleted = commit.startswith("00000000000000")  #re.match(r'[^1-9]+', commit)
print("7777",new_branch_push, branch_deleted)
#if new_branch_push:
#  print("8888", new_branch_push.group(0))
contains_commit_msg = False
MSG_TIP = ""


#print("zzzz",base,commit)
#exit(0)

if not ( new_branch_push or branch_deleted ):
    revs = base + "..." + commit
    #proc = subprocess.Popen(['git', 'rev-list', revs], stdout=subprocess.PIPE)
    #pushList = proc.stdout.readlines()
    #pushList = [x.strip() for x in pushList]
    #print("033333",pushList)
    #proc = subprocess.Popen(['git', 'show', pushList[0]], stdout=subprocess.PIPE)
    #print("04444444",proc.stdout.readlines())
    #exit(1)
    proc = subprocess.Popen(['git', 'rev-list','--oneline','--first-parent', revs], stdout=subprocess.PIPE)
    lines = proc.stdout.readlines()
    #print("66666",lines)
    if lines:
        #for line in lines:
        #    rev = str(line)
        #    match = re.search(r'FORCE') #re.search(r'TICKET-[0-9]{2,5}|#NEX-[0-9]{2,5}|HOTFIX|FORCE', rev)
        #    #print("1111", match)
        #    if match is not None:
        #        contains_commit_msg = True
        #        break
        (msg, flag) = _analysisCommitMsg(lines)
        print("55555555",msg,flag)
        if flag == 0 :
          contains_commit_msg = True
        else:
          MSG_TIP = msg

print("22222", contains_commit_msg or new_branch_push or branch_deleted)
#exit(1)


if contains_commit_msg or new_branch_push or branch_deleted:
    exit(0)
else:
    print MSG_TIP
    exit(1)